// <copyright file="CategoryService.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Models;
using EnterpriseApi.Repositories;

namespace EnterpriseApi.Services;

/// <summary>
/// 类别服务实现类，提供类别特有的业务逻辑操作
/// </summary>
public class CategoryService : Service<Category>, ICategoryService
{
    private readonly ICategoryRepository _categoryRepository;

    /// <summary>
    /// 初始化CategoryService的新实例
    /// </summary>
    /// <param name="categoryRepository">类别仓储</param>
    public CategoryService(ICategoryRepository categoryRepository) : base(categoryRepository)
    {
        _categoryRepository = categoryRepository;
    }

    /// <summary>
    /// 根据类别名称获取类别
    /// </summary>
    /// <param name="name">类别名称</param>
    /// <returns>类别对象，如果不存在则返回null</returns>
    public async Task<Category?> GetByNameAsync(string name)
    {
        return await _categoryRepository.GetByNameAsync(name);
    }

    /// <summary>
    /// 检查类别名称是否已存在
    /// </summary>
    /// <param name="name">类别名称</param>
    /// <returns>类别名称是否已存在</returns>
    public async Task<bool> IsNameExistsAsync(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("类别名称不能为空", nameof(name));
        }

        return await _categoryRepository.IsNameExistsAsync(name);
    }

    /// <summary>
    /// 创建新类别
    /// </summary>
    /// <param name="category">类别信息</param>
    /// <returns>创建的类别</returns>
    public async Task<Category> CreateCategoryAsync(Category category)
    {
        if (category == null)
        {
            throw new ArgumentNullException(nameof(category));
        }

        if (string.IsNullOrWhiteSpace(category.Name))
        {
            throw new ArgumentException("类别名称不能为空", nameof(category.Name));
        }

        // 检查类别名称是否已存在
        if (await _categoryRepository.IsNameExistsAsync(category.Name))
        {
            throw new ArgumentException($"类别名称 '{category.Name}' 已存在", nameof(category.Name));
        }

        category.CreatedAt = DateTime.UtcNow;
        category.UpdatedAt = null;

        return await _categoryRepository.AddAsync(category);
    }
}